/**
 * 预览表格组件
 * 处理数据预览的表格渲染和分页
 */
class PreviewTable {
    constructor(containerId, options = {}) {
        this.containerId = containerId;
        this.container = document.getElementById(containerId);
        this.options = {
            pageSize: options.pageSize || 20,
            showPagination: options.showPagination !== false,
            showStats: options.showStats !== false,
            sortable: options.sortable !== false,
            ...options
        };
        
        this.currentPage = 1;
        this.totalRecords = 0;
        this.data = [];
        this.columns = [];
        this.sortColumn = null;
        this.sortDirection = 'asc';
        
        this.init();
    }
    
    /**
     * 初始化组件
     */
    init() {
        if (!this.container) {
            console.error(`预览表格容器 "${this.containerId}" 不存在`);
            return;
        }
        
        this.render();
    }
    
    /**
     * 渲染表格
     */
    render() {
        this.container.innerHTML = this.getTemplate();
        this.bindEvents();
    }
    
    /**
     * 获取表格模板
     */
    getTemplate() {
        return `
            <div class="preview-table-container">
                ${this.renderStats()}
                ${this.renderTable()}
                ${this.renderPagination()}
            </div>
        `;
    }
    
    /**
     * 渲染统计信息
     */
    renderStats() {
        if (!this.options.showStats) return '';
        
        const startRecord = (this.currentPage - 1) * this.options.pageSize + 1;
        const endRecord = Math.min(this.currentPage * this.options.pageSize, this.totalRecords);
        
        return `
            <div class="flex justify-between items-center mb-4 p-3 bg-slate-50 rounded-lg">
                <div class="text-sm text-slate-600">
                    显示第 <span class="font-medium text-slate-900">${startRecord}</span> 到 
                    <span class="font-medium text-slate-900">${endRecord}</span> 条，
                    共 <span class="font-medium text-slate-900">${this.totalRecords}</span> 条记录
                </div>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-slate-600">
                        每页显示：
                        <select id="pageSizeSelect" class="ml-1 px-2 py-1 border border-slate-300 rounded text-sm">
                            <option value="10" ${this.options.pageSize === 10 ? 'selected' : ''}>10</option>
                            <option value="20" ${this.options.pageSize === 20 ? 'selected' : ''}>20</option>
                            <option value="50" ${this.options.pageSize === 50 ? 'selected' : ''}>50</option>
                            <option value="100" ${this.options.pageSize === 100 ? 'selected' : ''}>100</option>
                        </select>
                    </div>
                    <div class="text-sm text-slate-600">
                        执行时间：<span class="font-medium text-slate-900">${this.executionTime || 0}ms</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 渲染表格
     */
    renderTable() {
        if (this.data.length === 0) {
            return `
                <div class="text-center py-8 text-slate-500">
                    <i class="fas fa-inbox text-4xl mb-4"></i>
                    <p>暂无数据</p>
                </div>
            `;
        }
        
        const tableHtml = `
            <div class="overflow-x-auto border border-slate-200 rounded-lg">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            ${this.renderHeader()}
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-slate-200">
                        ${this.renderBody()}
                    </tbody>
                </table>
            </div>
        `;
        
        return tableHtml;
    }
    
    /**
     * 渲染表头
     */
    renderHeader() {
        return this.columns.map(column => {
            const sortIcon = this.getSortIcon(column);
            const sortableClass = this.options.sortable ? 'cursor-pointer hover:bg-slate-100' : '';
            
            return `
                <th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider ${sortableClass}"
                    data-column="${column}"
                    onclick="${this.options.sortable ? `previewTable.sort('${column}')` : ''}">
                    <div class="flex items-center">
                        <span>${this.formatColumnName(column)}</span>
                        ${sortIcon}
                    </div>
                </th>
            `;
        }).join('');
    }
    
    /**
     * 渲染表体
     */
    renderBody() {
        return this.data.map((row, index) => `
            <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-slate-50'} hover:bg-slate-100">
                ${this.columns.map(column => `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-900">
                        ${this.formatCellValue(row[column], column)}
                    </td>
                `).join('')}
            </tr>
        `).join('');
    }
    
    /**
     * 渲染分页
     */
    renderPagination() {
        if (!this.options.showPagination || this.totalRecords <= this.options.pageSize) {
            return '';
        }
        
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        
        return `
            <div class="flex items-center justify-between mt-4">
                <div class="flex items-center space-x-2">
                    <button onclick="previewTable.goToPage(1)" 
                            ${this.currentPage === 1 ? 'disabled' : ''}
                            class="px-3 py-1 border border-slate-300 rounded hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-angle-double-left"></i>
                    </button>
                    <button onclick="previewTable.previousPage()" 
                            ${this.currentPage === 1 ? 'disabled' : ''}
                            class="px-3 py-1 border border-slate-300 rounded hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-angle-left"></i>
                    </button>
                </div>
                
                <div class="flex items-center space-x-1">
                    ${this.renderPageNumbers(totalPages)}
                </div>
                
                <div class="flex items-center space-x-2">
                    <button onclick="previewTable.nextPage()" 
                            ${this.currentPage === totalPages ? 'disabled' : ''}
                            class="px-3 py-1 border border-slate-300 rounded hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-angle-right"></i>
                    </button>
                    <button onclick="previewTable.goToPage(${totalPages})" 
                            ${this.currentPage === totalPages ? 'disabled' : ''}
                            class="px-3 py-1 border border-slate-300 rounded hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-angle-double-right"></i>
                    </button>
                </div>
            </div>
        `;
    }
    
    /**
     * 渲染页码
     */
    renderPageNumbers(totalPages) {
        const current = this.currentPage;
        const delta = 2; // 当前页前后显示的页数
        
        let start = Math.max(1, current - delta);
        let end = Math.min(totalPages, current + delta);
        
        const pages = [];
        
        // 第一页
        if (start > 1) {
            pages.push(1);
            if (start > 2) {
                pages.push('...');
            }
        }
        
        // 中间页码
        for (let i = start; i <= end; i++) {
            pages.push(i);
        }
        
        // 最后一页
        if (end < totalPages) {
            if (end < totalPages - 1) {
                pages.push('...');
            }
            pages.push(totalPages);
        }
        
        return pages.map(page => {
            if (page === '...') {
                return '<span class="px-2 py-1 text-slate-500">...</span>';
            }
            
            const isActive = page === current;
            return `
                <button onclick="previewTable.goToPage(${page})" 
                        class="px-3 py-1 ${isActive ? 'bg-indigo-600 text-white' : 'border border-slate-300 hover:bg-slate-50'} rounded">
                    ${page}
                </button>
            `;
        }).join('');
    }
    
    /**
     * 获取排序图标
     */
    getSortIcon(column) {
        if (!this.options.sortable) return '';
        
        if (this.sortColumn === column) {
            const icon = this.sortDirection === 'asc' ? 'fas fa-sort-up' : 'fas fa-sort-down';
            return `<i class="${icon} ml-1 text-slate-400"></i>`;
        }
        
        return '<i class="fas fa-sort ml-1 text-slate-300"></i>';
    }
    
    /**
     * 格式化列名
     */
    formatColumnName(column) {
        const nameMap = {
            'id': 'ID',
            'name': '名称',
            'created_at': '创建时间',
            'updated_at': '更新时间',
            'status': '状态',
            'type': '类型'
        };
        
        return nameMap[column] || column.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
    }
    
    /**
     * 格式化单元格值
     */
    formatCellValue(value, column) {
        if (value === null || value === undefined || value === '') {
            return '<span class="text-slate-400">-</span>';
        }
        
        // 日期格式化
        if (column.includes('time') || column.includes('date')) {
            try {
                const date = new Date(value);
                if (!isNaN(date.getTime())) {
                    return date.toLocaleString('zh-CN');
                }
            } catch (e) {
                // 忽略日期解析错误
            }
        }
        
        // 布尔值格式化
        if (typeof value === 'boolean') {
            return value ? '<span class="text-green-600">是</span>' : '<span class="text-red-600">否</span>';
        }
        
        // 长文本截断
        if (typeof value === 'string' && value.length > 50) {
            return `<span title="${value}">${value.substring(0, 50)}...</span>`;
        }
        
        // 数字格式化
        if (typeof value === 'number') {
            return new Intl.NumberFormat('zh-CN').format(value);
        }
        
        return String(value);
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            pageSizeSelect.addEventListener('change', (e) => {
                this.options.pageSize = parseInt(e.target.value);
                this.currentPage = 1;
                this.onPageChange();
            });
        }
    }
    
    /**
     * 加载数据
     */
    async loadData(data, columns, totalRecords, executionTime = 0) {
        this.data = data;
        this.columns = columns || (data.length > 0 ? Object.keys(data[0]) : []);
        this.totalRecords = totalRecords || data.length;
        this.executionTime = executionTime;
        
        this.render();
    }
    
    /**
     * 排序
     */
    sort(column) {
        if (!this.options.sortable) return;
        
        if (this.sortColumn === column) {
            this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            this.sortColumn = column;
            this.sortDirection = 'asc';
        }
        
        this.data.sort((a, b) => {
            let aVal = a[column];
            let bVal = b[column];
            
            // 处理空值
            if (aVal == null && bVal == null) return 0;
            if (aVal == null) return this.sortDirection === 'asc' ? -1 : 1;
            if (bVal == null) return this.sortDirection === 'asc' ? 1 : -1;
            
            // 数字比较
            if (typeof aVal === 'number' && typeof bVal === 'number') {
                return this.sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
            }
            
            // 字符串比较
            aVal = String(aVal).toLowerCase();
            bVal = String(bVal).toLowerCase();
            
            if (this.sortDirection === 'asc') {
                return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
            } else {
                return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
            }
        });
        
        this.render();
    }
    
    /**
     * 跳转到指定页
     */
    goToPage(page) {
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        if (page < 1 || page > totalPages) return;
        
        this.currentPage = page;
        this.onPageChange();
    }
    
    /**
     * 上一页
     */
    previousPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            this.onPageChange();
        }
    }
    
    /**
     * 下一页
     */
    nextPage() {
        const totalPages = Math.ceil(this.totalRecords / this.options.pageSize);
        if (this.currentPage < totalPages) {
            this.currentPage++;
            this.onPageChange();
        }
    }
    
    /**
     * 页码变化回调
     */
    onPageChange() {
        this.render();
        
        // 触发自定义事件
        const event = new CustomEvent('pageChange', {
            detail: {
                page: this.currentPage,
                pageSize: this.options.pageSize
            }
        });
        this.container.dispatchEvent(event);
    }
    
    /**
     * 导出数据
     */
    exportData(format = 'csv') {
        try {
            if (this.data.length === 0) {
                alert('暂无数据可导出');
                return;
            }
            
            let content = '';
            let filename = `data_export_${new Date().toISOString().split('T')[0]}`;
            let mimeType = '';
            
            if (format === 'csv') {
                // CSV格式
                const headers = this.columns.join(',');
                const rows = this.data.map(row => 
                    this.columns.map(col => {
                        const value = row[col];
                        // 处理包含逗号或引号的值
                        if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
                            return `"${value.replace(/"/g, '""')}"`;
                        }
                        return value;
                    }).join(',')
                ).join('\n');
                
                content = headers + '\n' + rows;
                filename += '.csv';
                mimeType = 'text/csv';
            } else if (format === 'json') {
                // JSON格式
                content = JSON.stringify(this.data, null, 2);
                filename += '.json';
                mimeType = 'application/json';
            } else {
                alert('不支持的导出格式');
                return;
            }
            
            // 创建下载链接
            const blob = new Blob([content], { type: mimeType });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            // 显示成功提示
            console.log(`数据导出成功: ${filename}`);
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败，请重试');
        }
    }
}

// 导出为全局变量
window.PreviewTable = PreviewTable;